import { createLogger } from '../utils/Logger.js';
import { opsClient } from '../utils/OpsClient.js';
import { fetchUserOpsToken } from '../utils/OpsUser.js';
import { getProjectOpsFile, getGlobalOpsFile } from "../utils/OpsFile.js";
import { StrUtil } from "../utils/StrUtil.js";
import { FeishuBot } from "../utils/BotClient.js";
import inquirer from "inquirer";
import chalk from 'chalk';
import { OPSConstant } from "../constant/OPSConstant.js";

class FbdCommandHandler {
    constructor() {
        this.logger = createLogger('FBD');
        this.projectOpsFile = getProjectOpsFile();
        this.globalOpsFile = getGlobalOpsFile();
        this.opsUser = this.globalOpsFile.read('ops_user');
    }

    async initClient() {
        const token = await fetchUserOpsToken(this.opsUser);
        this.opsClient = opsClient(token, false);
    }

    async execute(args) {
        try {
            await this.initClient();

            if (!args || args.length === 0) {
                const flowId = await this.projectOpsFile.read('flow.id');
                const flowType = await this.projectOpsFile.read('flow.flow_type');

                if (!flowId || !flowType) {
                    this.logger.error('未找到发布单信息，请先执行 nb init 或指定应用名称');
                    return;
                }

                this.logger.info(`使用当前发布单: flow_type=${flowType}, flow_id=${flowId}`);
                await this.handleFlowBatch(flowId, flowType);
                return;
            }

            const input = args[0];

            if (input.startsWith('http')) {
                const urlObj = new URL(input);
                const flowType = urlObj.searchParams.get('flow_type');
                const flowId = urlObj.searchParams.get('flow_id');

                if (!flowType || !flowId) {
                    throw new Error('无效的发布单 URL，缺少 flow_type 或 flow_id 参数');
                }

                await this.handleFlowBatch(flowId, flowType);
            } else {
                await this.handleSingleApp(input);
            }
        } catch (error) {
            this.logger.error(`执行失败: ${error.message}`);
            if (error.stack) {
                this.logger.debug(error.stack);
            }
        }
    }

    async handleFlowBatch(flowId, flowType) {
        this.logger.info(`发布单类型: ${flowType}, ID: ${flowId}`);

        const appList = await this.opsClient.getAppAndBranch(flowId, flowType);
        if (!appList || appList.length === 0) {
            throw new Error('发布单中没有应用');
        }

        this.logger.info(`发布单包含 ${appList.length} 个应用: ${appList.map(a => a.app).join(', ')}`);

        const buildResults = [];
        for (const appInfo of appList) {
            this.logger.info(`\n开始构建 ${appInfo.app}...`);
            try {
                const { res: buildResult, startTime } = await this.triggerBuild(appInfo.app, appInfo, 'ft');
                buildResults.push({
                    appName: appInfo.app,
                    appInfo: appInfo,
                    buildResult: buildResult,
                    startTime: startTime,
                    status: 'building'
                });
            } catch (e) {
                this.logger.error(`${appInfo.app} 构建触发失败: ${e.message}`);
                buildResults.push({
                    appName: appInfo.app,
                    appInfo: appInfo,
                    status: 'failed',
                    error: e.message
                });
            }
        }

        this.logger.info('\n正在监控所有应用的构建状态(支持左右键切换查看)...');

        // TUI State
        const appStates = buildResults.map(r => ({
            appName: r.appName,
            status: r.status,
            logs: [],
            warImage: null
        }));

        let activeIndex = 0;
        let isRunning = true;
        const readline = await import('readline');

        // Setup TUI
        if (process.stdin.isTTY) {
            readline.emitKeypressEvents(process.stdin);
            process.stdin.setRawMode(true);
        }

        const render = () => {
            if (!isRunning) return;
            // 尝试清空滚动缓冲区
            process.stdout.write('\u001b[3J');
            console.clear();
            const currentApp = appStates[activeIndex];
            console.log(chalk.cyan(`\n=== 监控面板 (←/→ 切换应用, Ctrl+C 退出) ===`));
            console.log(`当前应用 [${activeIndex + 1}/${appStates.length}]: ${chalk.bold(currentApp.appName)}`);

            let statusColor = chalk.yellow;
            if (currentApp.status === 'success') statusColor = chalk.green;
            if (currentApp.status === 'failed' || currentApp.status === 'error') statusColor = chalk.red;
            if (currentApp.status === 'deploying' || currentApp.status === 'starting') statusColor = chalk.blue;

            console.log(`状态: ${statusColor(currentApp.status)}`);
            if (currentApp.warImage) {
                console.log(`镜像: ${chalk.green(currentApp.warImage)}`);
            }
            console.log(chalk.gray(`----------------------------------------`));

            const termHeight = process.stdout.rows || 24;
            const maxLogs = Math.max(5, termHeight - 8);
            const showLogs = currentApp.logs.slice(-maxLogs);
            console.log(showLogs.join('\n'));
        };

        const onKeypress = (str, key) => {
            if (key.name === 'left') {
                activeIndex = (activeIndex - 1 + appStates.length) % appStates.length;
                render();
            } else if (key.name === 'right') {
                activeIndex = (activeIndex + 1) % appStates.length;
                render();
            } else if (key.ctrl && key.name === 'c') {
                cleanup();
            }
        };

        if (process.stdin.isTTY) {
            process.stdin.on('keypress', onKeypress);
        }

        let resolveExit;
        const exitPromise = new Promise(r => resolveExit = r);

        const cleanup = () => {
            if (!isRunning) return;
            isRunning = false;
            if (process.stdin.isTTY) {
                process.stdin.setRawMode(false);
                process.stdin.removeListener('keypress', onKeypress);
            }
            resolveExit();
        };

        // Parallel Monitoring
        const promises = buildResults.map(async (result, index) => {
            if (result.status === 'failed') return;

            const loggerOverride = (type, msg) => {
                const logMsg = `[${new Date().toLocaleTimeString()}] ${msg}`;
                appStates[index].logs.push(logMsg);
                // 限制日志数量，防止内存溢出
                if (appStates[index].logs.length > 100) {
                    appStates[index].logs.shift();
                }
                if (index === activeIndex) render();
            };

            try {
                const isBaseApp = (await this.projectOpsFile.readList('flow.jz.app.names') || []).includes(result.appName);
                const warImage = await this.monitorBuild(
                    result.appName,
                    result.appInfo.id,
                    result.buildResult,
                    result.startTime,
                    loggerOverride,
                    isBaseApp
                );

                if (warImage) {
                    appStates[index].warImage = warImage;
                    appStates[index].logs.push(`构建成功: ${warImage}`);

                    appStates[index].status = 'deploying';
                    if (index === activeIndex) render();

                    await this.deployToStable(result.appName, warImage, loggerOverride);

                    appStates[index].status = 'starting';
                    if (index === activeIndex) render();

                    await this.monitorStartup(result.appName, warImage, loggerOverride);

                    appStates[index].status = 'success';
                    appStates[index].logs.push('流程完成');
                } else {
                    appStates[index].status = 'failed';
                    appStates[index].logs.push('构建失败: 未获取到镜像');
                }
            } catch (e) {
                appStates[index].status = 'error';
                appStates[index].logs.push(`异常: ${e.message}`);
            }
            if (index === activeIndex) render();
        });

        render();
        await Promise.all(promises);

        this.logger.success('\n所有应用处理完成！按 Ctrl+C 退出查看');
        render();

        await exitPromise;
    }

    async handleSingleApp(appName) {
        this.logger.info(`正在处理应用: ${appName}`);

        const flowId = await this.projectOpsFile.read('flow.id');
        const flowType = await this.projectOpsFile.read('flow.flow_type');
        if (!flowId || !flowType) {
            throw new Error('发布单信息缺失，请先执行 nb init');
        }

        const appList = await this.opsClient.getAppAndBranch(flowId, flowType);

        let targetAppName = appName;
        let appInfo = appList.find(a => a.app === targetAppName);

        if (!appInfo) {
            // 尝试解析应用名称 (普通应用)
            const opsName = await this.projectOpsFile.read(`flow.${appName}.opsName`);
            if (opsName) {
                targetAppName = opsName;
                appInfo = appList.find(a => a.app === targetAppName);
            }
        }

        if (!appInfo) {
            // 尝试解析应用名称 (基座应用)
            const jzOpsName = await this.projectOpsFile.read(`flow_jz.${appName}.opsName`);
            if (jzOpsName) {
                targetAppName = jzOpsName;
                appInfo = appList.find(a => a.app === targetAppName);
            }
        }

        if (!appInfo) {
            throw new Error(`在发布单中未找到应用: ${appName}`);
        }

        if (targetAppName !== appName) {
            this.logger.info(`应用名称已解析: ${appName} -> ${targetAppName}`);
            appName = targetAppName;
        }

        this.logger.info(`开始构建 ${appName} (Feature-Tag)...`);
        const { res: buildResult, startTime } = await this.triggerBuild(appName, appInfo, 'ft');

        this.logger.info(`正在监控构建状态...`);
        const jzAppNames = await this.projectOpsFile.readList('flow.jz.app.names') || [];
        const isBaseApp = jzAppNames.includes(appName);
        const warImage = await this.monitorBuild(appName, appInfo.id, buildResult, startTime, null, isBaseApp);

        if (!warImage) {
            this.logger.error('构建失败或未获取到镜像信息');
            return;
        }

        this.logger.success(`${appName} 构建成功!, 发布 stable 环境`);

        await this.deployToStable(appName, warImage);
        await this.monitorStartup(appName, warImage);
    }

    async getServerNodeEnv(appName, environment) {
        const appData = await this.opsClient.appEnv(appName);
        const zone = appData.zone;
        let envName = environment;
        if (zone === 'gl') {
            envName = 'stable';
        }
        const keys = [
            ...Object.keys(appData.server_nodes || {}),
            ...Object.keys(appData.server_nodes_prod || {})
        ];
        const matchedKey = keys.find(k => k.includes(envName));
        return {
            matchedKey,       // 找到的节点 key
            appData    // 原始数据
        };
    }

    async getImageVersion(appName, environment) {
        const { matchedKey, appData } = await this.getServerNodeEnv(appName, environment);
        if (!matchedKey) {
            throw new Error(`${environment} 环境信息不存在`);
        }
        const envData = await this.opsClient.podV2(appName, matchedKey);
        let podEnvData = null;
        for (const key of Object.keys(envData)) {
            const current = envData[key];
            if (environment === 'feature') {
                if (environment === 'ft' && current?.attached?.version?.rid) {
                    if (!current?.attached?.version) {
                        podEnvData = current;
                    }
                    break;
                }
            }
            podEnvData = current;
        }
        if (!podEnvData || Object.keys(podEnvData).length === 0) {
            throw new Error(`${environment} 环境信息key 不存在`);
        }
        const image = podEnvData.status.app_status.image;
        const imageKey = StrUtil.getLastPath(image);
        const imageVersionData = await this.opsClient.imageVersion(appName, imageKey);
        return {
            matchedKey,
            appData,
            imageVersionData,
            imageKey
        }
    }

    async triggerBuild(appName, appInfo, env) {
        const startTime = Date.now();
        const branch = await this.getFlowAppBranch(appName);
        this.logger.info(`${appName} 分支：${branch}`);

        // 检查是否是基座应用
        const jzAppNames = await this.projectOpsFile.readList('flow.jz.app.names');
        if (jzAppNames && jzAppNames.includes(appName)) {
            this.logger.info(`${appName} 是基座应用，将使用发布单构建接口触发构建...`);
        }

        this.logger.info(`正在调用构建API: flowAppId=${appInfo.id}`);
        this.logger.info(`API URL: /app/api/v1/flow/build_and_deploy/${appInfo.id}`);

        const res = await this.opsClient.buildAndDeploy(appInfo.id);

        this.logger.info(`构建API响应: ${JSON.stringify(res)}`);

        if (!res) {
            throw new Error('构建API返回空响应');
        }

        if (res.status && res.status !== 'success') {
            throw new Error(`构建失败: ${res.message || res.status}`);
        }

        return { res, startTime };
    }

    async monitorBuild(appName, flowAppId, buildResult, startTime, loggerOverride = null, isBaseApp = false) {
        const log = (type, msg) => {
            if (loggerOverride) {
                loggerOverride(type, msg);
            } else {
                if (type === 'write') process.stdout.write(msg);
                else if (this.logger[type]) this.logger[type](msg);
                else if (type === 'log') console.log(msg);
                else this.logger.info(msg);
            }
        };

        let retries = 0;
        // 初始等待，让服务器有时间创建记录
        await new Promise(r => setTimeout(r, 3000));

        while (true) {
            await new Promise(r => setTimeout(r, 5000));

            let history;
            try {
                history = await this.opsClient.buildHistory(flowAppId);
            } catch (e) {
                log('warn', `获取构建历史失败: ${e.message}`);
                retries++;
                if (retries > 5) throw e;
                continue;
            }

            if (!history || history.length === 0) {
                if (!loggerOverride) log('write', '.');
                continue;
            }

            const latestBuild = history[0];

            // 校验构建时间，确保是新触发的任务
            // 允许 30 秒的时间误差（服务器时间可能慢于本地时间）
            const buildTime = new Date(latestBuild.ctime || latestBuild.create_time).getTime();
            if (startTime && buildTime < startTime - 30000) {
                if (!loggerOverride) log('write', '.');
                continue;
            }

            // 检查是否有子任务或 jobs (基座应用可能是 jobs)
            const subtasks = latestBuild.subtask || [];
            const jobs = latestBuild.jobs || [];



            if (subtasks.length === 0 && jobs.length === 0) {
                // 如果状态是 error/failed，不跳过，直接进入后续错误处理逻辑
                if (latestBuild.status === 'error' || latestBuild.status === 'failed') {
                    // fall through
                } else {
                    // 如果状态是 success 但没有子任务，可能是异常数据，或者还在初始化
                    if (latestBuild.status === 'success') {
                        log('warn', `构建记录状态为 ${latestBuild.status} 但无子任务信息`);
                    }
                    if (!loggerOverride) log('write', '.');
                    continue;
                }
            }

            // 优先使用 subtask，如果没有则尝试从 jobs 获取信息（针对基座）
            let status = latestBuild.status;
            let taskName = 'unknown';
            let warImage = null;

            if (subtasks.length > 0) {
                const subtask = subtasks[0];
                status = subtask.status;
                taskName = subtask.name;
                warImage = subtask.image || subtask.war_image || subtask.pkg_url;

                if (!warImage && subtask.payload?.build?.image) {
                    const imageInfo = subtask.payload.build.image;
                    if (imageInfo.path && imageInfo.tag) {
                        warImage = `harbor-globaltesting-szgds.hszq8.com/${imageInfo.path}:${imageInfo.tag}`;
                    }
                }
            } else if (jobs.length > 0) {
                // 基座应用逻辑
                // 优先查找与 appName 匹配的 job (基座自身)
                const baseJob = jobs.find(j => j.app?.name === appName);

                if (baseJob) {
                    // 只监控基座自身的 job
                    status = baseJob.status;
                    taskName = baseJob.name || 'Base App Build';

                    if (baseJob.payload?.build?.image) {
                        const imageInfo = baseJob.payload.build.image;
                        if (imageInfo.path && imageInfo.tag) {
                            warImage = `harbor-globaltesting-szgds.hszq8.com/${imageInfo.path}:${imageInfo.tag}`;
                        }
                    }
                } else {
                    // 找不到对应 job，回退到聚合状态
                    const allDone = jobs.every(j => ['success', 'error', 'canceled'].includes(j.status));
                    const anyError = jobs.some(j => j.status === 'error');
                    const anyRunning = jobs.some(j => ['running', 'create', 'wait'].includes(j.status));

                    if (anyError) status = 'error';
                    else if (anyRunning) status = 'running';
                    else if (allDone) status = 'success';

                    taskName = 'Base App Build'; // 聚合任务名

                    const firstJob = jobs[0];
                    if (firstJob.payload?.build?.image) {
                        const imageInfo = firstJob.payload.build.image;
                        if (imageInfo.path && imageInfo.tag) {
                            warImage = `harbor-globaltesting-szgds.hszq8.com/${imageInfo.path}:${imageInfo.tag}`;
                        }
                    }
                }
            }

            // 如果还没找到镜像，尝试从 latestBuild 顶层找
            if (!warImage) {
                warImage = latestBuild.image;
            }

            // 如果顶层状态是 error/failed，强制覆盖状态
            if (latestBuild.status === 'error' || latestBuild.status === 'failed') {
                status = latestBuild.status;
            }

            const statusMsg = `[监控] 当前状态: ${status}`;
            if (loggerOverride) log('log', statusMsg);
            else log('log', `\n${statusMsg}`);

            if (status === 'success') {
                log('success', '构建完成!');

                if (!warImage) {
                    log('error', '构建成功但未找到镜像信息');
                    log('info', `构建数据: ${JSON.stringify(latestBuild, null, 2)}`);
                    return null;
                }

                log('info', `镜像: ${warImage}`);
                return warImage;
            }

            if (status === 'error' || status === 'failed') {
                log('error', `构建失败: status=${status}`);
                return null;
            }

            if (!loggerOverride) log('write', '.');
        }
    }

    async deployToStable(appName, warImage, loggerOverride = null) {
        const log = (type, msg) => {
            if (loggerOverride) {
                loggerOverride(type, msg);
            } else {
                if (this.logger[type]) this.logger[type](msg);
                else this.logger.info(msg);
            }
        };

        log('info', '正在发布到 Stable 环境...');
        log('info', `部署镜像: ${warImage}`);

        const releaseName = `${appName.replace(/_/g, '-')}-hk-feature`;

        const payload = {
            release: releaseName,
            war_image: warImage,
            operator: this.opsUser
        };

        const response = await this.opsClient.request('/app/api/v1/apps/deploy_to_stable', 'POST', payload);

        if (response && (response.status === 'success' || response.code === 200)) {
            log('success', '发布指令已下发');
        } else {
            log('success', '发布指令已下发');
        }
    }

    async monitorStartup(appName, warImage, loggerOverride = null) {
        const log = (type, msg) => {
            if (loggerOverride) {
                loggerOverride(type, msg);
            } else {
                if (this.logger[type]) this.logger[type](msg);
                else this.logger.info(msg);
            }
        };

        log('info', '正在监控启动状态...');
        const envKey = 'hk-ptft-feature';

        while (true) {
            await new Promise(r => setTimeout(r, 10000));

            let podData;
            try {
                podData = await this.opsClient.request(`/app/api/v1/apps/podv2/${appName}/${envKey}?force=true`);

                if (!podData || podData === null) {
                    log('info', '等待新 Pod 创建...');
                    continue;
                }
            } catch (e) {
                log('warn', `获取 Pod 信息失败: ${e.message}`);
                continue;
            }

            const pods = podData;
            let found = false;
            let success = false;
            let targetPod = null;

            for (const key in pods) {
                const pod = pods[key];
                if (!pod) continue;

                const metadata = pod.metadata || {};
                const spec = pod.spec || {};
                const status = pod.status || {};

                if (metadata.namespace !== 'hspt-hk-feature') {
                    continue;
                }

                const initContainers = spec.init_containers || [];
                if (initContainers.length > 0 && initContainers[0].image === warImage) {
                    found = true;
                    targetPod = pod;

                    log('info', `找到目标 Pod: ${metadata.name}`);

                    const appStatus = status.app_status || {};
                    const appReady = appStatus.ready;

                    log('info', `应用状态: app_status.ready = ${appReady}`);

                    if (appReady === 3) {
                        success = true;
                        log('info', '应用已完全就绪 (ready=3)');
                    } else {
                        log('info', `应用还未就绪 (ready=${appReady}), 等待中...`);
                    }
                    break;
                }
            }

            if (success) {
                log('success', '应用启动成功!');
                await this.sendNotification(appName, targetPod, loggerOverride);
                break;
            } else if (found) {
                log('info', '应用正在启动中...');
            } else {
                log('info', '等待新 Pod 创建...');
            }
        }
    }

    async sendNotification(appName, podData, loggerOverride = null) {
        const log = (type, msg) => {
            if (loggerOverride) {
                loggerOverride(type, msg);
            } else {
                if (this.logger[type]) this.logger[type](msg);
                else this.logger.info(msg);
            }
        };

        const chatId = await this.projectOpsFile.read('project.chat_id');
        if (!chatId) {
            log('warn', '未配置 project.chat_id，无法发送飞书通知');
            return;
        }

        const flowName = await this.projectOpsFile.read('flow.ops_flow_name') || '未知发布单';
        const flowUrl = await this.projectOpsFile.read('flow.url') || '';

        const bot = new FeishuBot(chatId);

        const taskLog = {
            row: {
                type: 'app',
                name: appName,
                desc: `已成功部署到 Stable 环境`,
                time: podData.metadata?.creation_timestamp
                    ? this.formatCreationTime(podData.metadata.creation_timestamp)
                    : new Date().toLocaleString('zh-CN', { hour12: false })
            },
            branch: podData.spec?.init_containers?.[0]?.image?.split(':')?.[1]?.split('-')?.[0] || '未知分支'
        };

        let mentionedUserIds = [];
        try {
            const mentionContext = await this.collectNotificationEmails();
            const { emails } = mentionContext;
            if (emails && emails.length > 0) {
                mentionedUserIds = await bot.fetchUserIdsByEmails(emails);
                if (mentionedUserIds.length > 0) {
                    log('info', `通知成员：${emails.join(', ')}（${mentionedUserIds.length}个）`);
                }
            }
        } catch (error) {
            log('warn', `获取通知人员失败，将发送普通消息：${error.message}`);
        }

        try {
            await bot.sendAppLogs(
                [taskLog],
                flowName,
                flowUrl,
                'Stable (hk-ptft-feature)',
                mentionedUserIds,
                {
                    title: "🚀 应用部署成功",
                    introLines: [
                        `应用已成功部署到 Stable 环境`,
                        `Pod 名称: ${podData.metadata?.name || 'Unknown'}`,
                        `Pod IP: ${podData.status?.pod_ip || 'Unknown'}`,
                        `镜像: ${podData.spec?.init_containers?.[0]?.image || 'Unknown'}`
                    ],
                    timeLabel: "部署时间"
                }
            );
            log('success', '飞书通知已发送');
        } catch (error) {
            log('error', `飞书通知发送失败: ${error.message}`);
        }
    }

    async collectNotificationEmails() {
        if (!this.projectOpsFile) {
            return { emails: [] };
        }

        const developerAccounts = new Set();
        if (this.opsUser) {
            const normalized = this.opsUser.trim();
            if (normalized) {
                developerAccounts.add(normalized);
            }
        }

        const formatAccounts = (accounts) => Array.from(accounts)
            .map(account => account.trim())
            .filter(account => account)
            .map(account => account.includes('@') ? account : `${account}@hstong.com`);

        return {
            emails: formatAccounts(developerAccounts)
        };
    }

    formatCreationTime(timestamp) {
        if (!timestamp || typeof timestamp !== 'string') {
            return new Date().toLocaleString('zh-CN', { hour12: false });
        }
        try {
            const date = new Date(timestamp);
            return date.toLocaleString('zh-CN', { hour12: false });
        } catch (e) {
            return timestamp;
        }
    }

    async getFlowAppBranch(opsName) {
        let branch = null;
        let configPath = null;

        branch = await this.projectOpsFile.read(`flow.${opsName}.source.branch`);
        if (branch) {
            configPath = `flow.${opsName}`;
            this.logger.debug?.(`从普通应用配置读取到分支: ${branch}`);
        }

        if (!branch) {
            branch = await this.projectOpsFile.read(`flow_jz_plugin.${opsName}.source.branch`);
            if (branch) {
                configPath = `flow_jz_plugin.${opsName}`;
                this.logger.debug?.(`从基座插件配置读取到分支: ${branch}`);
            }
        }

        if (!branch) {
            const jzAppNames = await this.projectOpsFile.readList('flow.jz.app.names');
            if (jzAppNames && jzAppNames.includes(opsName)) {
                const plugins = await this.projectOpsFile.readList(`flow_jz.${opsName}.plugins`);
                if (plugins && plugins.length > 0) {
                    const firstPlugin = plugins[0];
                    branch = await this.projectOpsFile.read(`flow_jz_plugin.${firstPlugin}.source.branch`);
                    if (branch) {
                        configPath = `flow_jz_plugin.${firstPlugin}`;
                        this.logger.info(`${opsName} 是基座应用，使用插件 ${firstPlugin} 的分支: ${branch}`);
                    }
                }
            }
        }

        if (!branch) {
            throw new Error(`未找到应用 ${opsName} 的分支配置,请确认已执行 nb init 并且应用在发布单中`);
        }

        let gitPath = null;
        if (configPath) {
            gitPath = await this.projectOpsFile.read(`${configPath}.git.path`);
            if (!gitPath && configPath.includes('flow_jz_plugin')) {
                const pluginPath = await this.projectOpsFile.read(`${configPath}.path`);
                if (pluginPath) {
                    gitPath = pluginPath;
                }
            }
        }

        if (gitPath) {
            const targetBranch = await this.projectOpsFile.read(`git_merge.auto_merge_${gitPath}_${branch}`);
            if (targetBranch) {
                this.logger.info(`${opsName} 存在合并分支: ${targetBranch}`);
                return targetBranch;
            }
        }

        return branch;
    }
}

export async function execute(args) {
    const handler = new FbdCommandHandler();
    await handler.execute(args);
}
